package com.example.excel.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson.JSON;
import com.example.excel.excel.ComplexSubjectEasyExcel;
import com.example.excel.excel.OrderForm;
import com.example.excel.excel.Student;
import com.example.excel.util.EasyExcelUtilsV1;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;

/**
 * description :
 * author :kang
 * create :2021-11-24 21:10:00
 */
@Slf4j
@RestController
@RequestMapping("/testmachine")
public class Testmachine {


    @ApiOperation("导出")
    @GetMapping(value = "/testRobot")
    public void testRobot(HttpServletResponse response) throws IOException {
        ComplexSubjectEasyExcel excel = new ComplexSubjectEasyExcel()
                .setSubjectId("1001")
                .setSubjectName("库存现金")
                .setFirstBorrowMoney(BigDecimal.valueOf(100))
                .setNowBorrowMoney(BigDecimal.valueOf(100))
                .setNowCreditMoney(BigDecimal.valueOf(100))
                .setYearBorrowMoney(BigDecimal.valueOf(100))
                .setYearCreditMoney(BigDecimal.valueOf(100))
                .setEndBorrowMoney(BigDecimal.valueOf(100));
        ComplexSubjectEasyExcel excel1 = new ComplexSubjectEasyExcel()
                .setSubjectId("1001")
                .setSubjectName("库存现金")
                .setFirstBorrowMoney(BigDecimal.valueOf(100))
                .setNowBorrowMoney(BigDecimal.valueOf(100))
                .setNowCreditMoney(BigDecimal.valueOf(100))
                .setYearBorrowMoney(BigDecimal.valueOf(100))
                .setYearCreditMoney(BigDecimal.valueOf(100))
                .setEndBorrowMoney(BigDecimal.valueOf(100));
        ComplexSubjectEasyExcel excel2 = new ComplexSubjectEasyExcel()
                .setSubjectId("1002")
                .setSubjectName("库存现金2")
                .setFirstBorrowMoney(BigDecimal.valueOf(100))
                .setNowBorrowMoney(BigDecimal.valueOf(100))
                .setNowCreditMoney(BigDecimal.valueOf(100))
                .setYearBorrowMoney(BigDecimal.valueOf(100))
                .setYearCreditMoney(BigDecimal.valueOf(100))
                .setEndBorrowMoney(BigDecimal.valueOf(100));
        ComplexSubjectEasyExcel excel3 = new ComplexSubjectEasyExcel()
                .setSubjectId("1002")
                .setSubjectName("库存现金2")
                .setFirstBorrowMoney(BigDecimal.valueOf(100))
                .setNowBorrowMoney(BigDecimal.valueOf(100))
                .setNowCreditMoney(BigDecimal.valueOf(100))
                .setYearBorrowMoney(BigDecimal.valueOf(100))
                .setYearCreditMoney(BigDecimal.valueOf(100))
                .setEndBorrowMoney(BigDecimal.valueOf(100));
        ComplexSubjectEasyExcel excel4 = new ComplexSubjectEasyExcel()
                .setSubjectId("1002")
                .setSubjectName("库存现金2")
                .setFirstBorrowMoney(BigDecimal.valueOf(101))
                .setNowBorrowMoney(BigDecimal.valueOf(100))
                .setNowCreditMoney(BigDecimal.valueOf(100))
                .setYearBorrowMoney(BigDecimal.valueOf(100))
                .setYearCreditMoney(BigDecimal.valueOf(100))
                .setEndBorrowMoney(BigDecimal.valueOf(100));
        ComplexSubjectEasyExcel excel5 = new ComplexSubjectEasyExcel()
                .setSubjectId("1001")
                .setSubjectName("库存现金")
                .setFirstBorrowMoney(BigDecimal.valueOf(101))
                .setNowBorrowMoney(BigDecimal.valueOf(100))
                .setNowCreditMoney(BigDecimal.valueOf(100))
                .setYearBorrowMoney(BigDecimal.valueOf(100))
                .setYearCreditMoney(BigDecimal.valueOf(100))
                .setEndBorrowMoney(BigDecimal.valueOf(100));
        List<ComplexSubjectEasyExcel> excels = new ArrayList<>();
        excels.add(excel);
        excels.add(excel1);
        excels.add(excel2);
        excels.add(excel3);
        excels.add(excel4);
        excels.add(excel5);

        EasyExcelUtilsV1.defaultExportOssUrlResponse(excels, ComplexSubjectEasyExcel.class, response, "科目余额表", new HashMap<>());
    }

    @PostMapping("/exportExcel")
    public void exportExcel(HttpServletResponse response) throws Exception {
        String fileName = "报表";
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        fileName = URLEncoder.encode(fileName, "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();
        List<Student> studentList = new ArrayList<Student>();
        Student student = new Student("1", "张三", "2000-01-01");
        studentList.add(student);
        //这里 需要指定写用哪个class去写
        WriteSheet writeSheet = EasyExcel.writerSheet(0, "学生信息1").head(Student.class).build();
        excelWriter.write(studentList, writeSheet);
        writeSheet = EasyExcel.writerSheet(1, "学生信息2").head(Student.class).build();
        excelWriter.write(studentList, writeSheet);
        //千万别忘记finish 会帮忙关闭流
        excelWriter.finish();
    }

    @PostMapping("/importExcel")
    @ApiOperation(value = "通用下载请求", produces = "application/octet-stream")
    public void importExcel(@RequestPart("file") MultipartFile file, HttpServletResponse response) throws Exception {
        //解析execl文件file
        InputStream inputStream = file.getInputStream();
        List<OrderForm> readSyncList = EasyExcel.read(inputStream).head(OrderForm.class).sheet().headRowNumber(1).doReadSync();

        //将解析的数据导出成execl文件
        String fileName = "报表";
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        fileName = URLEncoder.encode(fileName, "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();

        for (OrderForm orderForm : readSyncList) {
            String body = HttpRequest.get("https://s.kwaixiaodian.com/rest/app/tts/ks/seller/order/detail?oid=" + orderForm.getNo() + "&frontPublishCacheSourceType=1")
                    .header("Cookie", "did=web_c2d4xjyb2j6fx56cqi0hfbtud81d32xx; kNginxAB=false; sid=kshop.api; userId=140000043769727; ks-s-ctn=4de0c902-5b16-4f3a-8bb1-2127a663f76c; kshop.api_st=Cgxrc2hvcC5hcGkuc3QSkAGv5LrG-tWfLfxo4Gvujx-7ebFfQkA8JXax_eIT9dh8DW5V4QNTeqegluplbziG6aP-fqhWPKp9SPSb_1p__9PyQtN195yuJBHgx4q8ZtLGKmMNrOHKIVT3YaHpxsvnz3RtqT86dB9dxVepwrK5heR-GdA9lSTGlBi88Om3rQbdowb39gZegGMPqtSqjd_eEaAaEqEimlfa4tOSp7v0b4_VagYG0CIgWuDAgk9sgk7qH4XkSVqMV2IlEs3ikHEkWKJygw9qAJsoBTAB; kshop.api_ph=99dc530d2ca7644c570de4d72a52d315129d; merchantSessionKey=1665238721100_d4156112aaa2495e217033097ce332a4")
                    .header("Referer", "https://s.kwaixiaodian.com/zone/order/detail?id=" + orderForm.getNo())
                    .header("content-type", "multipart/form-data; boundary=---011000010111000001101001")
                    .execute().body();
            System.out.println(body);
            //body字符串转成map
            Map<String, Object> parse = (Map<String, Object>) JSON.parse(body);
            if (ObjectUtil.isNotEmpty(parse.get("orderDetailView"))) {
                String orderDetailView = String.valueOf(parse.get("orderDetailView"));
                Map<String, Object> address = (Map<String, Object>) JSON.parse(orderDetailView);
                //获取收货人姓名
                String name = String.valueOf(address.get("consignee"));
                //商品数量
                String num = String.valueOf(address.get("num"));
                //实付款
                String payment = String.valueOf(address.get("orderTradeAmount"));
                //在payment后面加上小数点
                String payment1 = payment.substring(0, payment.length() - 2) + "." + payment.substring(payment.length() - 2);
                //下单时间
                Long createTime = (Long) address.get("createTime");
                //createTime转成时间
                String time = DateUtil.format(new Date(createTime), "yyyy-MM-dd HH:mm:ss");
                //获取收货人电话
                String phone = String.valueOf(address.get("mobile"));
                //获取收货人地址
                String addressDetail = address.get("province") + " " + address.get("city") + " " + address.get("district") + " " + address.get("address");
                orderForm.setNumber(num);
                orderForm.setPrice(payment1);
                orderForm.setCreateTime(time);
                orderForm.setName(name);
                orderForm.setPhone(phone);
                orderForm.setAddress(addressDetail);
                System.out.println("订单信息" + orderForm.toString());
            }

            //睡眠0.5秒
            Thread.sleep(1000);
        }

        //这里 需要指定写用哪个class去写
        WriteSheet writeSheet = EasyExcel.writerSheet(0, "订单信息").head(OrderForm.class).build();
        excelWriter.write(readSyncList, writeSheet);
        excelWriter.finish();
    }


}
